import json
import os
import re

from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse
from rest_framework.generics import RetrieveUpdateAPIView
from rest_framework.response import Response

from common import errors
from common.func import sendsms, create_token, login_decorate, check_code
from travel import settings
from user.models import User
from user.serializers import UserModelSerializers


def send_sms(request):
    # 1,获取数据
    phone = request.body.get('phone')

    # 2，判断数据
    # 判断手机号的格式
    if not re.match(r'^1[3-9]\d{9}$', phone):
        return JsonResponse({'code': errors.PHONE_FORMAT_ERROR, 'msg': '手机号格式不对'})

    # 3，处理逻辑
    # 发短信
    sendsms.delay(phone)

    # 4,返回响应
    return JsonResponse({'code': 0, 'msg': '发送成功'})


def register(request):

    # 1,获取数据
    data = json.loads(request.body)
    phone = data.get('phone')
    code = data.pop('code')

    # 2，判断数据
    # 2.1 判断手机号格式
    ser = UserModelSerializers(data=data)
    ser.is_valid()
    if ser.errors.get('phone'):
        error_code = ser.errors.get('phone')[0].code
        if error_code == errors.PHONE_FORMAT_ERROR:
            return JsonResponse({'code': errors.PHONE_FORMAT_ERROR, 'msg': '手机号格式不对'})
        elif error_code == 'unique':
            return JsonResponse({'code': errors.PHONE_EXIST, 'msg': '手机号已注册'})

    res = check_code(code, phone)
    if res:
        return res

    # 3，处理逻辑
    ser.save()

    # 保存用户用户的登陆状态
    token = create_token(ser.data['uid'])

    # 4，返回响应
    return JsonResponse({'code': 0, 'data': token})


def chgpsd(request):

    # 1,获取数据
    data = json.loads(request.body)
    phone = data.get('phone')
    code = data.get('code')
    password = data.get('password')

    # 2，判断验证码
    res = check_code(code, phone)
    if res:
        return res

    user = User.objects.filter(phone=phone).update(password=make_password(password))
    if not user:
        return JsonResponse({'code': errors.USER_NOT_EXIST, 'msg': '用户不存在'})
    print(User.objects.filter(phone=phone)[0].password)
    return JsonResponse({'code': 0, 'msg': '修改密码成功'})


def login(request):

    data = json.loads(request.body)
    phone = data.get('phone')
    password = data.get('password')
    user = User.objects.filter(phone=phone)
    if not user.exists():
        return JsonResponse({'code': errors.USER_NOT_EXIST, 'msg': '用户不存在'})
    if not check_password(password, user[0].password):
        return JsonResponse({'code': errors.PHONE_PASSWORD_ERROR, 'msg': '手机号或密码错误'})
    token = create_token(user[0].uid)
    return JsonResponse({'code': 0, 'data': token})


@login_decorate
def avatar(request):
    img = request.FILES.get('avatar')

    # 获取图片后缀
    ext = os.path.splitext(img.name)[1]
    img_name = f'avatar-{request.user.uid}{ext}'
    img_path = os.path.join(settings.BASE_DIR, f'uploads/{img_name}')

    with open(img_path, 'wb') as fp:
        for chunk in img.chunks():
            fp.write(chunk)
    return JsonResponse({'code': 0, 'data': img_path})


class UserView(RetrieveUpdateAPIView):
    queryset = User.objects.all()
    serializer_class = UserModelSerializers

    @login_decorate
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    @login_decorate
    def post(self, request, *args, **kwargs):
        return self.put(request, *args, **kwargs)



